<template id="home-content">
  <div class="container">
    <!-- 左侧区域：两行两列柱状图 -->
    <div class="container-wrap left-container">
      <item-wrap title="特征分析与流量识别">
        <div class="item">
          <div class="chart-wrapper">
            <!-- 两行两列柱状图布局 -->
            <div v-for="index in [0, 1, 2, 3]" :key="index" class="chart-container grid-2x2">
              <div class="bar-chart" :id="'bar-chart-' + index"></div>
              <div class="chart-title">UPF-{{ index }}</div>
            </div>
          </div>
        </div>
      </item-wrap>
    </div>
    
    <!-- 右侧区域：上部分两个视频，下部分折线图 -->
    <div class="container-wrap right-container">
      <item-wrap title="集中推理与联邦推理流程示意">
        <div class="item">
          <!-- 右侧上部分：两个视频 -->
          <div class="video-wrapper">
            <div class="video-container left-video">
              <video class="process-video" autoplay loop muted playsinline>
                <source src="@/assets/video/jizhong.mp4" type="video/mp4">
                您的浏览器不支持视频播放
              </video>
            </div>
            <div class="video-container right-video">
              <video class="process-video" autoplay loop muted playsinline>
                <source src="@/assets/video/lianbang.mp4" type="video/mp4">
                您的浏览器不支持视频播放
              </video>
            </div>
          </div>
          
          <!-- 右侧下部分：折线图 -->
          <div class="line-chart-container">
            <div class="line-chart" id="line-chart"></div>
          </div>
        </div>
      </item-wrap>
    </div>
  </div>
  <router-view />
</template>

<script>
import * as echarts from "echarts";
import { loadConfig } from "@/utils/config";
import axios from "axios";

export default {
  name: "Recognize",
  components: {},
  data() {
    return {
      interval: null,
      barChartInstances: [],
      trafficData: [
        { traffic1: 0, traffic2: 0 },
        { traffic1: 0, traffic2: 0 },
        { traffic1: 0, traffic2: 0 },
        { traffic1: 0, traffic2: 0 },
      ],
      lineChartInstance: null,
      nwdafData: [], // 存储从新API获取的数据
      maxDataPoints: 20, // 图表最大数据点数
      currentTime: 1, // 当前时间点
      lineChartTimes: [], // 新增：存储每个数据点的时间
    };
  },
  mounted() {
    this.initBarCharts();
    this.fetchBarChartData();
    this.interval = setInterval(this.fetchBarChartData, 2000);
    this.initLineChart();
    this.fetchLineChartData(); // 初始化获取折线图数据
    this.lineChartInterval = setInterval(this.fetchLineChartData, 1000); // 每5秒更新一次折线图数据
  },
  beforeUnmount() {
    this.barChartInstances.forEach((chart) => {
      chart.dispose();
    });
    if (this.lineChartInstance) {
      this.lineChartInstance.dispose();
    }
    if (this.interval) {
      clearInterval(this.interval);
    }
    if (this.lineChartInterval) {
      clearInterval(this.lineChartInterval);
    }
  },
  methods: {
    initBarCharts() {
      this.trafficData.forEach((item, index) => {
        const barChartDom = document.getElementById(`bar-chart-${index}`);
        const barChart = echarts.init(barChartDom);

        const barOption = {
          tooltip: {
            trigger: "axis",
            axisPointer: {
              type: "shadow",
            },
          },
          grid: {
            left: "10%",
            right: "10%",
            top: "10%",
            bottom: "10%",
          },
          xAxis: {
            type: "category",
            data: ["业务1", "业务2"],
            axisLabel: {
              color: "#fff",
              fontSize: 20,
            },
          },
          yAxis: {
            type: "value",
            show: true,
            axisLabel: {
              show: false,
            },
            min: 0,
            max: 4500,
          },
          series: [
            {
              data: [
                {
                  value: item.traffic1,
                  itemStyle: {
                    color: "#4BC0C0",
                  },
                },
                {
                  value: item.traffic2,
                  itemStyle: {
                    color: "#4BC0C0",
                  },
                },
              ],
              type: "bar",
              barWidth: "40%",
              label: {
                show: true,
                position: "top",
                color: "#fff",
              },
            },
          ],
        };

        barChart.setOption(barOption);
        this.barChartInstances.push(barChart);

        window.addEventListener("resize", () => {
          barChart.resize();
        });
      });
    },

    updateBarCharts(newData) {
      this.trafficData = newData;
      this.trafficData.forEach((item, index) => {
        const barChart = this.barChartInstances[index];
        if (barChart) {
          const barOption = {
            series: [
              {
                data: [
                  {
                    value: item.traffic1,
                    itemStyle: {
                      color: "#4BC0C0",
                    },
                  },
                  {
                    value: item.traffic2,
                    itemStyle: {
                      color: "#4BC0C0",
                    },
                  },
                ],
              },
            ],
          };
          barChart.setOption(barOption);
        }
      });
    },
    async fetchBarChartData() {
      try {
        const config = await loadConfig();
        const apiUrl = config.apiUrl;
        const response = await axios.get(`${apiUrl}/get_path`);
        
        if (response.data && response.data.length > 0) {
          this.trafficData[0].traffic1 = response.data[0].upf0_prediction_1 || 0;
          this.trafficData[0].traffic2 = response.data[0].upf0_prediction_2 || 0;
          this.trafficData[1].traffic1 = response.data[0].upf1_prediction_1 || 0;
          this.trafficData[1].traffic2 = response.data[0].upf1_prediction_2 || 0;
          this.trafficData[2].traffic1 = response.data[0].upf2_prediction_1 || 0;
          this.trafficData[2].traffic2 = response.data[0].upf2_prediction_2 || 0;
          this.trafficData[3].traffic1 = response.data[0].upf3_prediction_1 || 0;
          this.trafficData[3].traffic2 = response.data[0].upf3_prediction_2 || 0;
          
          this.updateBarCharts(this.trafficData);
        }
      } catch (error) {
        console.error("获取柱状图数据失败:", error);
        // 模拟数据用于本地测试
        this.trafficData = this.trafficData.map(item => ({
          traffic1: 0,
          traffic2: 0
        }));
        this.updateBarCharts(this.trafficData);
      }
    },

    initLineChart() {
      const lineChartDom = document.getElementById("line-chart");
      this.lineChartInstance = echarts.init(lineChartDom);

      const lineOption = {
        tooltip: {
          trigger: "axis",
        },
        // title: {

        // },
        grid: {
          left: "13%",
          right: "10%",
          bottom: "30%",
          top: "15%",
        },
        legend: {
          bottom: 40,
          data: ["传输数据量"],
          textStyle: {
            color: "#fff",
            fontSize: 20,
          },
        },
        xAxis: {
          type: "category",
          name: "时间",
          nameTextStyle: {
            color: "#fff",
            fontSize: 20,
          },
          axisLabel: {
            color: "#fff",
            rotate: 0,
          },
        },
        yAxis: {
          type: "value",
          name: "传输数据量(log10(Mb/s))",
          nameTextStyle: {
            color: "#fff",
            fontSize: 20,
          },
          axisLabel: {
            color: "#fff",
          },
          min: -5,
          max: 5,
        },
        series: [
          {
            name: "传输数据量",
            type: "line",
            smooth: true,
            data: [],
            itemStyle: {
              color: "#00BFFF", // 蓝色线条
            },
            symbolSize: 6, // 数据点大小
            lineStyle: {
              width: 2, // 线条宽度
            }
          },
        ],
      };

      this.lineChartInstance.setOption(lineOption);
    },
    async fetchLineChartData() {
      try {
        // 从指定API获取数据
        const response = await axios.get("http://10.112.51.79:39898/get_nf_data?nf=nwdaf");
        
        if (response.data) {
          // 提取net_io_list的第一个值
          const netIoValue = response.data.net_io_list[response.data.net_io_list.length - 1] || 0;
          let logValue = 0;
          if (netIoValue !== 0) {
            logValue = Math.log10(netIoValue);
          }
          
          console.log("netIoValue:", netIoValue, "logValue:", logValue);
          // 更新图表数据
          this.updateLineChart(logValue);
        }
      } catch (error) {
        console.error("获取折线图数据失败:", error);
        // 模拟数据用于本地测试
        this.updateLineChart(0);
      }
    },
    updateLineChart(value) {
      // 获取当前图表数据
      const chartOption = this.lineChartInstance.getOption();
      const lineData = chartOption.series[0].data;
      
      // 添加新数据点
      lineData.push(value);

      // 记录当前时间
      const now = new Date();
      const minutes = String(now.getMinutes()).padStart(2, '0');
      const seconds = String(now.getSeconds()).padStart(2, '0');
      this.lineChartTimes.push(`${minutes}:${seconds}`);
      
      // 保持数据点数量不超过最大值
      if (lineData.length > this.maxDataPoints) {
        lineData.shift();
        this.lineChartTimes.shift(); // 同时移除最早的时间
      }
      
      // 更新图表
      this.lineChartInstance.setOption({
        xAxis: {
          data: this.lineChartTimes,
        },
        series: [{ 
          data: lineData,
        }],
      });
      
      // 更新当前时间点
      this.currentTime++;
    },
  },
};
</script>

<style scoped>
.container {
  display: flex;
  height: 80%;
  width: 100%;
  justify-content: center;
  margin-top: 20px;
  font-size: 30px;
}

.container-wrap {
  width: 100%;
  height: 100%;
  display: flex;
}

.left-container {
  flex: 2; /* 左侧区域宽度 */
}

.right-container {
  flex: 3; /* 右侧区域宽度 */
}

.item {
  width: 100%;
  height: 100%;
  position: relative;
}

/* 左侧柱状图布局样式 */
.chart-wrapper {
  display: flex;
  flex-wrap: wrap;
  width: 100%;
  height: 400px;
}

.grid-2x2 {
  flex: 1 1 45%; /* 两行两列布局 */
  max-width: 50%;
  box-sizing: border-box;
}

.chart-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.2);
  border-radius: 8px;
}

.bar-chart {
  width: 100%;
  height: 90%;
  margin-top: 0;
}

.chart-title {
  font-size: 20px;
  color: "#fff";
  text-align: center;
  margin-top: 10px;
  font-weight: normal;
}

/* 右侧视频布局样式 */
.video-wrapper {
  display: flex;
  width: 100%;
  height: 60%; /* 视频区域占右侧高度的60% */
  margin-bottom: 20px;
}

.video-container {
  flex: 1;
  height: 100%;
  position: relative;
  overflow: hidden;
  border-radius: 8px;
  background-color: rgba(0, 0, 0, 0.2);
}

.left-video, .right-video {
  padding: 10px;
}

.process-video {
  width: 200%;
  height: 200%;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-38%, -45%);
  object-fit: contain;
  border-radius: 4px;
}

/* 右侧折线图样式 */
.line-chart-container {
  width: 100%;
  height: 40%; /* 折线图区域占右侧高度的40% */
}

.line-chart {
  width: 100%;
  height: 100%;
}
</style>